package com.sgb.kjwl.view.ui.activity.supplier3;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.amap.api.maps.MapView;
import com.amap.api.maps.model.Marker;
import com.sgb.alimaplibrary.MapMarkerTools;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySupplier3Binding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.supplier3.SupplierRecommendEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.adapter.supplier3.SupplierRecommendAdapter;
import com.sgb.kjwl.view.widget.DictWindow3;
import com.sgb.kjwl.view.widget.MapInfoDialog4;
import com.sgb.kjwl.view.widget.MapInfoWindow4;
import com.sgb.kjwl.view.widget.MultiWindow3;
import com.sgb.kjwl.viewmodel.supplier3.SupplierModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

public class SupplierActivity3 extends AppActivity {
    public static final String TYPE_LIST = "列表";
    public static final String TYPE_MAP = "地图";
    private ActivitySupplier3Binding binding;
    private SupplierRecommendAdapter supplierRecommendAdapter;
    private DictWindow3 supplierCityWindow3;
    private DictWindow3 supplierDistanceWindow3;
    private DictWindow3 supplierSortWindow3;
    private MultiWindow3 supplierTypeWindow3;
    @Inject
    SupplierModel3 viewModel;

    private Double currentLat;
    private Double currentLong;
    private List<SupplierRecommendEntity> mapSupplierList;
    private Map conditionMap;
    private List<DictEntity3> cityDictEntityList;
    private List<DictEntity3> distanceDictEntityList;
    private List<DictEntity3> sortDictEntityList;
    private List<DictEntity3> typeEntityList;
    private int intMap;
    private EditText searchText;

    private BigDecimal getlatitude;
    private BigDecimal getlongitude;

    public MapMarkerTools mapMarkerTools;
    List<SupplierRecommendEntity> bundles = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, SupplierActivity3.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, int map) {
        Intent intent = new Intent();
        intent.putExtra("map", map);
        intent.setClass(context, SupplierActivity3.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder()
                .appComponent(appComponent)
                .homeModule(new HomeModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mapMarkerTools = new MapMarkerTools(getActivity(),getLifecycle());
        initView(savedInstanceState);
    }
    /**
     *
     */
    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(SupplierActivity3.this, R.layout.activity_supplier3);
        binding.setViewModel(viewModel);
        intMap = getIntent().getIntExtra("map", 0);
        searchText = binding.include.etView;
        binding.include.ivBack.setOnClickListener(this);
        binding.include.rightView.setOnClickListener(this);
        binding.include.tvSearch.setOnClickListener(this);
        binding.cityLayout.setOnClickListener(this);
        binding.distanceLayout.setOnClickListener(this);
        binding.sortLayout.setOnClickListener(this);

        if (supplierRecommendAdapter == null) {
            supplierRecommendAdapter = new SupplierRecommendAdapter(SupplierActivity3.this, null);
        }
        if (intMap != 0) {//地图模式下文字显示为列表,显示定位按钮
            binding.include.rightView.setText(TYPE_LIST);
            binding.listLayout.setVisibility(View.GONE);
            binding.mapView.setVisibility(View.VISIBLE);
            //binding.sortView.setVisibility(View.GONE);
            binding.include.tvSearch.setVisibility(View.VISIBLE);
            binding.include.vLine.setVisibility(View.VISIBLE);
            binding.include.rightView.setText(TYPE_LIST);
        } else {//列表模式下文字显示为地图,隐藏定位按钮
            //binding.sortView.setVisibility(View.VISIBLE);
            binding.include.tvSearch.setVisibility(View.GONE);
            binding.include.vLine.setVisibility(View.GONE);
            binding.include.rightView.setText(TYPE_MAP);
            Map  map = new HashMap();
            map.put("latitude", currentLat);
            map.put("longitude", currentLong);
            Log.e("tagmapaddress",map.toString() );
            viewModel.getSupplierListModel(map, false);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(SupplierActivity3.this);
        binding.rlvList.setLayoutManager(layoutManager);
        binding.rlvList.addItemDecoration(new RecyclerCustomDecoration(0,
                0,
                0,
                getResources().getDimension(R.dimen.dp5), getResources().getColor(R.color.color_F5F5F5)));
        binding.rlvList.setAdapter(supplierRecommendAdapter);

        supplierRecommendAdapter.setOnItemClick(new AdapterOnItemClick<SupplierRecommendEntity>() {
            @Override
            public void onItemClick(SupplierRecommendEntity supplierRecommendEntity, int position) {
                if (TextUtils.isEmpty(supplierRecommendEntity.getCompanyId())){
                    ToastUtil.show(getActivity(),"企业店铺id不能为空");
                    return;
                }
                ShopInfoForCompanyTradesActivity.startAct(getActivity(), supplierRecommendEntity.getCompanyId(), "", 0, 0);
            }
        });

        binding.rlvList.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                Map  map = new HashMap();
                map.put("latitude", currentLat);
                map.put("longitude", currentLong);
                Log.e("tagmapaddress",map.toString() );
                viewModel.getSupplierListModel(map, false);
            }

            @Override
            public void onLoadMore() {
                Map  map = new HashMap();
                map.put("latitude", currentLat);
                map.put("longitude", currentLong);
                viewModel.getSupplierListModel(map, true);
            }
        });

        supplierCityWindow3 = new DictWindow3(SupplierActivity3.this);
        supplierCityWindow3.setOnCallBack(new DictWindow3.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                currentLat = Double.valueOf(dictEntity.getLatitude());
                currentLong = Double.valueOf(dictEntity.getLongitude());
                //设置经纬度以查询地图模式下的数据
                conditionMap.put("latitude", currentLat);
                conditionMap.put("longitude", currentLong);
                conditionMap.put("cityNo", dictEntity.getId());
                if (intMap == 0){
                    viewModel.getSupplierListModel(conditionMap, false);
                }else{
                    viewModel.getSupplierMapModel(conditionMap);
                    cameraToPosition();
                }
            }
        });
        supplierDistanceWindow3 = new DictWindow3(SupplierActivity3.this);
        supplierDistanceWindow3.setOnCallBack(new DictWindow3.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                conditionMap.put("distance", dictEntity.getId());
                if (intMap == 0){
                    viewModel.getSupplierListModel(conditionMap, false);
                }else{
                    viewModel.getSupplierMapModel(conditionMap);
                }
            }
        });
        supplierSortWindow3 = new DictWindow3(SupplierActivity3.this);
        supplierSortWindow3.setOnCallBack(new DictWindow3.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                conditionMap.put("intellectId", dictEntity.getId());
                viewModel.getSupplierListModel(conditionMap, false);
            }
        });
        supplierTypeWindow3 = new MultiWindow3(SupplierActivity3.this);

        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                conditionMap.put("name", searchText.getText().toString());
                viewModel.getSupplierListModel(conditionMap, false);
            }
        });

    }

    @Override
    protected void init() {
        conditionMap = new HashMap();
        //viewModel.getSupplierCityModel();
//        viewModel.getPickupLocationModel();
        viewModel.getDistanceModel();
        viewModel.getSupplierSortModel();
        searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    conditionMap.put("name", searchText.getText().toString());
                    conditionMap.put("latitude", currentLat);
                    conditionMap.put("longitude", currentLong);
                    viewModel.getSupplierListModel(conditionMap, false);
                    return true;
                }
                return false;
            }
        });
    }

    private void initView(Bundle savedInstanceState) {
        initMap(savedInstanceState);
    }

    private void initMap(Bundle savedInstanceState) {
        MapView mMapView = binding.mapView;
        mapMarkerTools.init(savedInstanceState, mMapView);
        mapMarkerTools.setMarkerClick(new MapMarkerTools.MarkerClick() {
            @Override
            public void onMarkerClick(int pos,String title) {
                showMarkerView(pos,title);
            }

            @Override
            public void onMarkerClick(int pos, String title, Marker marker) {

            }

            @Override
            public void onLocationChanged(Double Lat, Double Log,String address) {
                if (currentLat == null || currentLat <= 0){
                    currentLat = Lat;
                    currentLong =  Log;
                    //设置经纬度以查询地图模式下的数据
                    conditionMap.put("latitude", currentLat);
                    conditionMap.put("longitude",currentLong);
                    if (intMap == 0){
                        viewModel.getSupplierListModel(conditionMap, false);
                    }else{
                        viewModel.getSupplierMapModel(conditionMap);
                        cameraToPosition();
                    }
                }
            }

            @Override
            public void getAddress(Double Lat, Double Log, String address) {

            }

            @Override
            public void failure() {

            }
        });
    }

    public boolean showMarkerView(int pos,String title) {
        SupplierRecommendEntity entity = bundles.get(pos);
        MapInfoWindow4 mapInfoWindow = new MapInfoWindow4(this);
        mapInfoWindow.setData(entity);

        new MapInfoDialog4(SupplierActivity3.this, null)
                .setDialogClickCallBack(new MapInfoDialog4.DialogClickCallBack() {
                    @Override
                    public void onClickShop(String shopId) {
                        if (TextUtils.isEmpty(shopId)){
                            ToastUtil.show(getActivity(),"企业店铺id不能为空");
                            return;
                        }
                        ShopInfoForCompanyTradesActivity.startAct(getActivity(), shopId, "", 0, 0);
                    }
                })
                .setData(mapInfoWindow.getData()).show();
        return false;
    }

    public void showList(List<SupplierRecommendEntity> datas, boolean isLoadMore) {
        if (isLoadMore) {
            binding.rlvList.loadMoreComplete();
            if (datas.size() != 0) {
                supplierRecommendAdapter.addDatas(datas);
            }
        } else {
            if (datas.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }
            binding.rlvList.refreshComplete();
            binding.rlvList.setLoadingMoreEnabled(true);
            supplierRecommendAdapter.setDatas(datas);
        }
    }

    public void showLocation(MapLongAndLatEntity mapLongAndLatEntity) {
        if (mapLongAndLatEntity != null) {
            currentLat = Double.valueOf(mapLongAndLatEntity.getLat());
            currentLong = Double.valueOf(mapLongAndLatEntity.getLng());

            //设置经纬度以查询地图模式下的数据
            conditionMap.put("latitude", currentLat);
            conditionMap.put("longitude", currentLong);
            viewModel.getSupplierMapModel(conditionMap);
            cameraToPosition();
        }
    }

    public void showCityPopWindow(List<DictEntity3> data) {
        this.cityDictEntityList = data;
        if (cityDictEntityList != null && cityDictEntityList.size() > 0) {
            currentLat = Double.valueOf(data.get(0).getLatitude());
            currentLong = Double.valueOf(data.get(0).getLongitude());
            conditionMap.put("cityNo", data.get(0).getId());
            //设置经纬度以查询地图模式下的数据
            conditionMap.put("latitude", currentLat);
            conditionMap.put("longitude", currentLong);
            if (intMap == 0){
                viewModel.getSupplierListModel(conditionMap, false);
            }else{
                viewModel.getSupplierMapModel(conditionMap);
                cameraToPosition();
            }

        }
        supplierCityWindow3.setData(data);
    }

    public void showDistancePopWindow(List<DictEntity3> data) {
        this.distanceDictEntityList = data;
        if (data != null && data.size() > 0) {
            //未选择距离时设置一个最大默认距离
            conditionMap.put("distance", data.get(data.size() - 1).getId());
            if (intMap == 0){
                viewModel.getSupplierListModel(conditionMap, false);
            }else{
                viewModel.getSupplierMapModel(conditionMap);
            }
        }
        supplierDistanceWindow3.setData(data);
    }

    public void showSortPopWindow(List<DictEntity3> data) {
        this.sortDictEntityList = data;
        supplierSortWindow3.setData(data);
    }

    public void showTypePopWindow(List<DictEntity3> data) {
        this.typeEntityList = data;
        supplierTypeWindow3.setData(data);
    }

    public void showMap(List<SupplierRecommendEntity> datas) {
        mapSupplierList = datas;
        addMarkInfoWindow(mapSupplierList);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_search://定位
                Intent intent = new Intent();
                intent.setClass(SupplierActivity3.this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择定位地址");
                intent.putExtra(SelectAddressActivity.LATITUDE, currentLat);
                intent.putExtra(SelectAddressActivity.LONGTITUDE, currentLong);
                startActivityForResult(intent, 101);
                break;
            case R.id.right_view://列表和地图切换
                if (binding.include.rightView.getText().toString().equals(TYPE_MAP)) {
                    binding.include.rightView.setText(TYPE_LIST);
                    binding.listLayout.setVisibility(View.GONE);
                    binding.mapView.setVisibility(View.VISIBLE);
                    binding.include.tvSearch.setVisibility(View.VISIBLE);
                    binding.include.vLine.setVisibility(View.VISIBLE);
                    //binding.sortView.setVisibility(View.GONE);
                    viewModel.getSupplierMapModel(conditionMap);
                } else {
                    binding.include.rightView.setText(TYPE_MAP);
                    binding.listLayout.setVisibility(View.VISIBLE);
                    binding.mapView.setVisibility(View.GONE);
                    binding.include.tvSearch.setVisibility(View.GONE);
                    binding.include.vLine.setVisibility(View.GONE);
                    //binding.sortView.setVisibility(View.VISIBLE);

                    viewModel.getSupplierListModel(conditionMap, false);
                }
                break;
            case R.id.city_layout://城市筛选
                supplierCityWindow3.showPopwindow(binding.cityLayout);
                if (cityDictEntityList == null) {
                    viewModel.getSupplierCityModel();
                }
                break;
            case R.id.distance_layout://距离筛选
                supplierDistanceWindow3.showPopwindow(binding.distanceLayout);
                if (distanceDictEntityList == null) {
                    viewModel.getDistanceModel();
                }
                break;
            case R.id.sort_layout://智能排序
                supplierSortWindow3.showPopwindow(binding.sortLayout);
                if (sortDictEntityList == null) {
                    viewModel.getSupplierSortModel();
                }
                break;
        }
    }

    private void addMarkInfoWindow(List<SupplierRecommendEntity> datas) {
        try {
            mapMarkerTools.mapClear();
            bundles.clear();
            for (int i = 0; i < datas.size(); i++) {
                if (null != datas && datas.size() > 0) {
                    SupplierRecommendEntity entity = datas.get(i);
                    if (null != entity && !TextUtils.isEmpty(entity.getLatitude()) && !TextUtils.isEmpty(entity.getLongitude())) {
                        double currentLat = Double.parseDouble(entity.getLatitude());
                        double currentLong = Double.parseDouble(entity.getLongitude());
                        if (currentLat == 0 || currentLong == 0) {
                            return;
                        }
                        mapMarkerTools.addPoiItem(currentLat, currentLong,"");
                        bundles.add(datas.get(i));
                    }
                }
            }
            mapMarkerTools.addAllMarkerToMap(R.mipmap.ic_map_overlay,false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //设置定位点
    private void cameraToPosition() {
        mapMarkerTools.setMyLocation(currentLat,currentLong);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            currentLat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            currentLong = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            conditionMap.put("latitude", currentLat);
            conditionMap.put("longitude", currentLong);
            if (intMap==0){
                viewModel.getSupplierListModel(conditionMap, false);
            }else{
                //设置经纬度以查询地图模式下的数据
                viewModel.getSupplierMapModel(conditionMap);
                cameraToPosition();
            }

        }
    }
}
